package com.frame.project.common;

import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 字符串缓存
 * @author Administrator
 *
 */

public class StringRedisUtil {
	private static Logger logger = LogManager.getLogger(StringRedisUtil.class);
	
	public static StringRedisTemplate stringRedisTemplate; 
	
	public  void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {  
		StringRedisUtil.stringRedisTemplate = stringRedisTemplate;  
	}  
	
	/** 
	 * 普通缓存放入 
	 * @param key 键 
	 * @param value 值 
	 * @return true成功 false失败 
	 */  
	public static boolean set(String key,String value) {  
		try {  
			stringRedisTemplate.opsForValue().set(key, value);
			return true;  
		} catch (Exception e) {  
			e.printStackTrace();  
			return false;  
		}  

	}  
	
	
	/** 
	 * 普通缓存放入并设置时间 
	 * @param key 键 
	 * @param value 值 
	 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 
	 * @return true成功 false 失败 
	 */  
	public static boolean set(String key,String value,long time){  
		try {  
			if(time>0){  
				stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);  
			}else{  
				set(key, value);  
			}  
			return true;  
		} catch (Exception e) {  
			e.printStackTrace();  
			return false;  
		}  
	}  
	
	/** 
	 * 普通缓存获取 
	 * @param key 键 
	 * @return 值 
	 */  
	public static String get(String key){  
		return key==null?null:stringRedisTemplate.opsForValue().get(key);  
	} 
	
}
